package com.java.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.dao.HomeTemplateDao;
import com.java.service.ShopHomeTemplateService;
import com.java.util.CommonUtil;
import com.java.vo.ShopHomeTemplate;

/**
 * 专区模块
 */
@Controller
@RequestMapping("/shopHomeTemplate")
public class QueryShopHomeTemplateController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HomeTemplateDao homeTemplateDao;

    @Autowired
    ShopHomeTemplateService homeTemplateService;

    private static final String RETURN_FLAG = "return_flag";

    private static final String RETURN_MSG = "return_msg";

    private String toJsonStr(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// date类型转换格式
        mapper.setSerializationInclusion(Include.ALWAYS);// 设置为always 序列化时
                                                         // 保留null属性

        return mapper.writeValueAsString(obj).replace(":null", ":\"\"");// 将null转换为"-"
    }

    @RequestMapping(value = "/homeList", method = RequestMethod.POST)
    @ResponseBody
    public void getHomeList(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String areaName = jsonData.getString("areaName");
            String content = jsonData.getString("content");
            String summary = jsonData.getString("summary");
            String weight = jsonData.getString("weight");
            Integer page = jsonData.getInteger("page");

            List<ShopHomeTemplate> homeTemplates = homeTemplateDao.getShopHomeTemplate(areaName, content, summary,
                    weight, page);
            int Cnt = homeTemplateDao.getShopHomeTemplateCnt(areaName, content, summary, weight);
            if (homeTemplates != null) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("HomeTemplates", homeTemplates);
                jsonMap.put("cnt", Cnt);
            } else {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("HomeTemplates", null);
                jsonMap.put("cnt", Cnt);
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/homeTemplateDetail", method = RequestMethod.POST)
    @ResponseBody
    public void getHomeTemplateDetail(@RequestParam String Jdata, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            int id = jsonData.getIntValue("id");
            if (id <= 0) {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "id错误");
            } else {
                ShopHomeTemplate homeTemplate = homeTemplateService.getShopHomeTemplateById(id);
                if (homeTemplate != null) {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put("HomeTemplate", homeTemplate);
                } else {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put("HomeTemplate", null);
                }
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/addHomeTemplate", method = RequestMethod.POST)
    @ResponseBody
    public void addHomeTemplate(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String shopHomeTemplate = jsonData.getString("ShopHomeTemplate");
            ShopHomeTemplate sp = com.alibaba.fastjson.JSONObject.parseObject(shopHomeTemplate, ShopHomeTemplate.class);
            if (sp == null) {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "传入对象转换后为空");
            } else {
                sp.setStatus(false);// 新增后 先置未激活状态
                boolean id = homeTemplateService.addShopHomeTemplate(sp);
                if (id) {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put(RETURN_MSG, "操作成功");
                    jsonMap.put("id", id);
                } else {
                    jsonMap.put(RETURN_FLAG, false);
                    jsonMap.put(RETURN_MSG, "操作失败");
                }
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/updateHomeTemplate", method = RequestMethod.POST)
    @ResponseBody
    public void updateHomeTemplate(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String shopHomeTemplate = jsonData.getString("ShopHomeTemplate");
            ShopHomeTemplate sp = com.alibaba.fastjson.JSONObject.parseObject(shopHomeTemplate, ShopHomeTemplate.class);
            if (sp == null) {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "传入对象转换后为空");
            } else {
                ShopHomeTemplate spdb = homeTemplateService.getShopHomeTemplateById(sp.getId());
                sp.setStatus(spdb.isStatus());
                homeTemplateService.delShopHomeTemplateDetail(spdb, sp);
                logger.info("获取ShopHomeTemplate" + sp.toString());
                boolean id = homeTemplateService.updateShopHomeTemplate(sp);
                if (id) {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put(RETURN_MSG, "操作成功");
                    jsonMap.put("id", id);
                } else {
                    jsonMap.put(RETURN_FLAG, false);
                    jsonMap.put(RETURN_MSG, "操作失败");
                }
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/activateTemplate", method = RequestMethod.POST)
    @ResponseBody
    public void activateTemplate(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            Integer id = jsonData.getInteger("id");
            ShopHomeTemplate sp = homeTemplateService.getShopHomeTemplateById(id);
            if (sp == null) {
                throw new Exception("传入对象转换后为空");
            }
            sp.setHomeTemplateDetails(new ArrayList<>());
            sp.setStatus(!sp.isStatus());
            boolean flag = homeTemplateService.updateShopHomeTemplate(sp);
            if (flag) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put(RETURN_MSG, "操作成功");
                jsonMap.put("id", id);
            } else {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "操作失败");
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

}
